package com.lh.serverforwebrtc.service.impl;

import com.lh.serverforwebrtc.bean.RespBean;
import com.lh.serverforwebrtc.bean.SecurityCodeBean;
import com.lh.serverforwebrtc.bean.UserBean;
import com.lh.serverforwebrtc.mapper.SecurityCodeMapper;
import com.lh.serverforwebrtc.mapper.UserMapper;
import com.lh.serverforwebrtc.service.SecurityCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SecurityCodeServiceImpl implements SecurityCodeService {

    @Autowired
    private SecurityCodeMapper securityCodeMapper;

    @Autowired
    private UserMapper userMapper;



    @Override
    public boolean addSeCode(SecurityCodeBean codeBean) {
        return securityCodeMapper.insertCode(codeBean);
    }

    @Override
    public RespBean verifyPhone(Long userPhone,int code) {
        SecurityCodeBean securityCodeBean = securityCodeMapper.queryCodeByPhone(userPhone);
        //判断验证码是否一样
        if (code == securityCodeBean.getVerifiCode()){
            //user表中查询是否注册该手机号码
             UserBean userByPhone = userMapper.findUserByPhone(userPhone);
             if (userByPhone != null){
                 //user表中存在该手机号码
                 userByPhone.setUserPassword(null);
                 //删除Code验证码记录
                 securityCodeMapper.deleteCodeByPhone(userPhone);
                 return RespBean.success("登录成功",userByPhone);
             }else {
                 //user表中不存在该手机号码，默认注册新用户
                 UserBean userBean = new UserBean();
                 userBean.setUserPhone(userPhone);
                 userBean.setUserAvatar("http://192.168.1.123:8787/avatar/default.webp");
                 userBean.setUserAddress("月球");
                 userMapper.insertUser(userBean);
                 //注册成功后，删除code验证码记录，通过userPhone，删除security_code表中的该条数据
                 securityCodeMapper.deleteCodeByPhone(userPhone);
                 return RespBean.newUser("注册成功", userBean);
             }
        }else {
            return RespBean.error("验证码错误");
        }
    }
}
